var goods = {};
var uid ;
$(document).ready(function () {
  if(isLogin()!=undefined){
    $.ajax({
      type:"get",
      url:"http://localhost:3301/user?phone="+isLogin(),
      async:false,
      success:function(data){
        uid = data[0].id;
      }
    })
  }
  let id = parseUrl().id;
  let good = [];
  if (parseUrl().id == undefined || parseUrl().id == "") {
    location.href = "list.html";
  }
  $.ajax({
    type: "get",
    url: "http://localhost:3301/goods?id=" + id,
    async: false,
    success: function (data) {
      good = data[0];
      $(".sku-name h4").html(good.goods_name);
      $(".price em").html(good.goods_price + ".00");
    }
  })
  $.ajax({
    type: "get",
    url: "http://localhost:3301/spec_goods?goods_id=" + id,
    async: false,
    success: function (data) {
      if(data.length==0){
        return;
      }
      //存储规格信息
      let spec_goods = new Map();
      let spec_data = [];
      spec_data = data;
      data.forEach((e, i) => {
        let specs = e.value_names.split(" ");
        specs.forEach((e, i) => {
          let key = e.split(":")[0];
          let val = e.split(":")[1];
          let spec = spec_goods.get(key);
          if (spec == undefined) {
            spec_goods.set(key, new Set([val]));
          } else {
            spec_goods.get(key).add(val);
          }
        })
      })
      //展示规格信息
      let specification = $("#specification");
      spec_goods.forEach((v, k) => {
        let dl = $("<dl>");
        let dt = $(`<dt><div class="fl title"><i>${k}</i></div></dt>`);
        dl.append(dt);
        v.forEach((e) => {
          let dd = $(`<dd><a href="javascript:;">${e}<span title="点击取消选择">&nbsp;</span></a></dd>`);
          dl.append(dd);
        })
        specification.append(dl);
      })
      select_spec(spec_data[0].value_names);
      $("#specification dd").click(function () {
        $(this).siblings("dd").find("a").removeClass("selected");
        $(this).find("a").addClass("selected");
        let k = "";
        if($(this).find("a").hasClass("locked")){
          k=$(this).siblings("dt").find("i").text()+":"+$(this).find("a").text();
        }else{
          $(".selected").each((i, e) => {
            k += $(e).parents("dl").find("dt i").html() + ":" + $.trim($(e).text()) + " ";
          })
        }
        k = $.trim(k);
        select_spec(k);
      })
      function select_spec(e) {
        let spec_goods = [];
        $.ajax({
          type: "get",
          url: `http://localhost:3301/spec_goods?goods_id=${id}&value_names=${encodeURIComponent(e)}`,
          async: false,
          success: function (data) {
            let dd = new Map();
            let spec = data[0];
            spec_goods = data[0];
            $("#specification dd a").addClass("locked");
            if(spec!=undefined){
              spec.value_names.split(" ").forEach((e,i)=>{
                let key = e.split(":")[0];
                let val = e.split(":")[1];
                $(`#specification .title i:contains("${key}")`).parents("dl").find(`dd a`).removeClass("selected");
                $(`#specification .title i:contains("${key}")`).parents("dl").find(`dd a:contains("${val}")`).addClass("selected");
                $.ajax({
                  type:"get",
                  url: `http://localhost:3301/spec_goods?goods_id=${id}&value_names_like=${key}:${encodeURIComponent(val.replace("+","\\+"))}`,
                  async:false,
                  success:function(da){
                    da.forEach((e,i)=>{
                      e.value_names.split(" ").forEach((e1,i1)=>{
                        let k = e1.split(":")[0];
                        let v = e1.split(":")[1];
                        if(dd.get(k)==undefined){
                          dd.set(k,new Set());
                          dd.get(k).add(v);
                        }else{
                          dd.get(k).add(v);
                        }
                      })
                    })
                  }
                })
              })
            }else{
              $.ajax({
                type:"get",
                url:`http://localhost:3301/spec_goods?goods_id=${id}&value_names_like=${encodeURIComponent(e.replace("+","\\+"))}`,
                async:false,
                success:function(data){
                  spec_goods = data[0];
                  select_spec(data[0].value_names);
                }
              })
            }
            dd.forEach((v,k)=>{
              v.forEach((e,i)=>{
                $(`#specification .title i:contains("${k}")`).parents("dl").find(`dd a:contains("${e}")`).removeClass("locked");
              })
            })
            $(".summary-wrap .price em").html(spec_goods.price);
            goods.spec_goods_id=spec.id;
          }
        })
      }
    }
  })
  //展示导航
  $.get("http://localhost:3301/category?id="+good.cate_id).done((data)=>{
    let c = data[0];
    $(".sui-breadcrumb li:eq(2) a").html(c.cate_name);
    $.get("http://localhost:3301/category?id="+c.pid).done((data)=>{
      let c = data[0];
      $(".sui-breadcrumb li:eq(1) a").html(c.cate_name);
      $.get("http://localhost:3301/category?id="+c.pid).done((data)=>{
        let c = data[0];
        $(".sui-breadcrumb li:eq(0) a").html(c.cate_name);
      })
    })
  })
  $.get("http://localhost:3301/brand?id="+good.brand_id).done((data)=>{
    let b = data[0];
    $(".sui-breadcrumb li:eq(3)").html(b.cname);
  })
  $.get("http://localhost:3301/goods_images?goods_id="+good.id).done((data)=>{
    let item = $(".items ul");
    $(".jqzoom img").attr({"jqimg":data[0].pics_big,"src":data[0].pics_big});
    data.forEach((e,i)=>{
      let img = $(`<li><img src="${e.pics_sma}" onmousemove="preview(this)"></li>`);
      item.append(img);
    })
  })
  if(good.goods_attr!=""){
    JSON.parse(good.goods_attr).forEach((e,i)=>{
      $(".goods-intro").append($(`<li>${e.attr_name}：${e.attr_value}</li>`));
    })
  }
  add_cart();
  function add_cart(){
    let id = parseUrl().id;
    goods.is_selected = 0;
    goods.number = parseInt($("#number").val());
    if(uid!=undefined){
      goods.user_id = uid;
    }
    goods.goods_id=parseInt(good.id);
  }
  $("#plus").click(function(){
    if($("#number").val()>9){
      alert("限量10个");
      return;
    }
    $("#number").val(parseInt($("#number").val())+1);
    add_cart();
  })
  $("#mins").click(function(){
    if($("#number").val()==1){
      alert("不能再减了");
      return;
    }
    $("#number").val($("#number").val()-1);
    add_cart();
  })

  $(".btn-choose .addshopcar").click(function(){
    if(uid==undefined){
      if(getCookie("cart")==""||getCookie("cart")=="[]"){
        setCookie("cart",JSON.stringify([goods]),2);
      }else{
        let cart = JSON.parse(getCookie("cart"));
        for(let i = 0;i<cart.length;i++){
          if(cart[i].goods_id==goods.goods_id&&cart[i].spec_goods_id==goods.spec_goods_id){
            cart[i].number=cart[i].number+goods.number;
            setCookie("cart",JSON.stringify(cart),2);
            break;
          }else{
            cart.push(goods);
            setCookie("cart",JSON.stringify(cart),2);
            break;
          }
        }
      }
    }else{
      addOrPutCart(goods);
    }
    //添加到购物车成功
    var d = new Date();
    d.setTime(d.getTime() + (2 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = "success-cart" + "=" + JSON.stringify(goods) + ";" + expires + ";path=/";
  })
})


function preview(img) {
  $("#preview .jqzoom img").attr("src", $(img).attr("src"));
  $("#preview .jqzoom img").attr("jqimg", $(img).attr("bimg"));
}
//图片预览小图移动效果,页面加载时触发
$(function () {
  var tempLength = 0; //临时变量,当前移动的长度
  var viewNum = 5; //设置每次显示图片的个数量
  var moveNum = 2; //每次移动的数量
  var moveTime = 300; //移动速度,毫秒
  var scrollDiv = $(".spec-scroll .items ul"); //进行移动动画的容器
  var scrollItems = $(".spec-scroll .items ul li"); //移动容器里的集合
  var moveLength = scrollItems.eq(0).width() * moveNum; //计算每次移动的长度
  var countLength = (scrollItems.length - viewNum) * scrollItems.eq(0).width(); //计算总长度,总个数*单个长度

  //下一张
  $(".spec-scroll .next").bind("click", function () {
    if (tempLength < countLength) {
      if ((countLength - tempLength) > moveLength) {
        scrollDiv.animate({ left: "-=" + moveLength + "px" }, moveTime);
        tempLength += moveLength;
      } else {
        scrollDiv.animate({ left: "-=" + (countLength - tempLength) + "px" }, moveTime);
        tempLength += (countLength - tempLength);
      }
    }
  });
  //上一张
  $(".spec-scroll .prev").bind("click", function () {
    if (tempLength > 0) {
      if (tempLength > moveLength) {
        scrollDiv.animate({ left: "+=" + moveLength + "px" }, moveTime);
        tempLength -= moveLength;
      } else {
        scrollDiv.animate({ left: "+=" + tempLength + "px" }, moveTime);
        tempLength = 0;
      }
    }
  });
});